﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SQLite;

namespace Mark.Sqlite.Helper
{
	public class TableCreator : TableMapper
	{
		public string CreateSqlTable<T>() where T : class 
		{
			var obj = Activator.CreateInstance<T>();
			var map = MapEntity(obj);
			
			var cmdFields = string.Empty;
			foreach (var columnInfo in map.Columns)
			{
				var typeNull = Nullable.GetUnderlyingType(columnInfo.PropertyInfo.PropertyType);
				var type = typeNull ?? columnInfo.PropertyInfo.PropertyType;

				if (type == typeof(string) || type == typeof(char))
				{
					cmdFields += string.Format(" {0} {1} {2},",
						columnInfo.ColumnName, 
						(columnInfo.Lenght > 0 ? string.Format("VARCHAR({0})", columnInfo.Lenght) : "VARCHAR(255)"),
						(columnInfo.AllowNull ? "NULL" : "NOT NULL"));
				}
				else if (type == typeof(decimal) || type == typeof(float) || type == typeof(double))
				{
					cmdFields += string.Format(" {0} {1} {2},",
						columnInfo.ColumnName,
						"NUMERIC", 
						(columnInfo.AllowNull ? "NULL" : "NOT NULL"));
				}
				else if (type == typeof(bool) || type == typeof(byte))
				{
					cmdFields += string.Format(" {0} {1} {2},",
						columnInfo.ColumnName,
						"BOOLEAN", 
						(columnInfo.AllowNull ? "NULL" : "NOT NULL"));
				}
				else if ((type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64)) && columnInfo.IsAutoIncrement)
				{
					cmdFields += string.Format(" {0} {1} {2} {3},",
						columnInfo.ColumnName,
						"INTEGER",
						"NOT NULL PRIMARY KEY",
						(columnInfo.IsAutoIncrement ? "AUTOINCREMENT" : string.Empty));
				}
				else if (type == typeof(Int16) || type == typeof(Int32) || type == typeof(Int64))
				{
					cmdFields += string.Format(" {0} {1} {2},",
						columnInfo.ColumnName,
						"INTEGER",
						(columnInfo.AllowNull ? "NULL" : "NOT NULL"));
				}
				else if (type == typeof(byte[]))
				{
					cmdFields += string.Format(" {0} {1} {2},",
						columnInfo.ColumnName,
						"BLOB",
						(columnInfo.AllowNull ? "NULL" : "NOT NULL"));
				}
				
			}

			cmdFields = cmdFields.Remove(cmdFields.LastIndexOf(",", StringComparison.Ordinal));

			//SO VAI CRIAR SE NAO EXISTIR NENHUM AUTO-INCREMENTO
			var cmdPk = string.Empty;
			if (!map.Columns.Any(t => t.IsAutoIncrement))
			{
				foreach (var columnInfo in map.Columns.Where(t => t.IsPrimaryKey))
				{
					cmdPk += string.Format("{0}, ", columnInfo.ColumnName);
				}

				if (!string.IsNullOrEmpty(cmdPk))
				{
					cmdPk = cmdPk.Remove(cmdPk.LastIndexOf(", ", StringComparison.Ordinal));
					cmdPk = string.Format(", PRIMARY KEY ({0})", cmdPk);
				}
			}


			var query = string.Format("CREATE TABLE IF NOT EXISTS {0} ({1} {2})", map.Table.TableName, cmdFields, cmdPk);
			
			return query;
		}


	}
}
